package com.example.wumeng.sugartest;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.wumeng.sugartest.bean.Book;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText etTitle;
    private EditText etAuthor;

    private Button btnSave;
    private Button btnQuery;
    private Button btnUpdate;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        /** 初始化视图 */
        initViews();
    }

    /** 初始化视图 */
    private void initViews() {
        etTitle = findViewById(R.id.et_title);
        etAuthor = findViewById(R.id.et_author);

        btnSave = findViewById(R.id.btn_save);
        btnQuery = findViewById(R.id.btn_query);
        btnUpdate = findViewById(R.id.btn_update);

        btnSave.setOnClickListener(this);
        btnQuery.setOnClickListener(this);
        btnUpdate.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_save:
                SugarSave();
                break;
            case R.id.btn_query:
                SugarQuery();
                break;
            case R.id.btn_update:
                SugarUpdate();
                break;
            default:
                break;
        }
    }

    private void SugarSave() {
        Book book = new Book();
        book.setTitle(etTitle.getText().toString().trim());
        book.setAuthor(etAuthor.getText().toString().trim());
        book.save();
        Toast.makeText(this, "成功", Toast.LENGTH_SHORT).show();
    }

    private void SugarQuery() {
        Book book = Book.findById(Book.class,1);
        Toast.makeText(this,book.getTitle() + "@" + book.getAuthor(),Toast.LENGTH_LONG).show();
    }

    private void SugarUpdate() {
        Book book = Book.findById(Book.class,1);
        book.setTitle(etTitle.getText().toString().trim());
        book.setAuthor(etAuthor.getText().toString().trim());
        book.save();
    }
}
